package com.lk.client.rpc;

import com.lk.client.rpc.handler.InitializerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

/**
 * @author kun.li
 */
@Data
public class RpcClientManager {


    private static Channel channel = null;
    private static final Object LOCK_OBJ = new Object();

    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        synchronized (LOCK_OBJ) {
            if (channel != null) {
                return channel;
            }
            initChannel();
            return channel;
        }
    }


    public static void initChannel() {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture =
                    new Bootstrap()
                            .group(nioEventLoopGroup)
                            .channel(NioSocketChannel.class)
                            .handler(new InitializerHandler())
                            .connect("localhost", 8585);
            channel = channelFuture.sync().channel();
            channel.closeFuture().addListener((ChannelFutureListener) channelFuture1 -> {
                nioEventLoopGroup.shutdownGracefully();
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
